package utils

import (
	beego "github.com/beego/beego/v2/adapter"
	"github.com/go-redis/redis"
)

var redisClient *redis.Client

func init()  {
	InitRedis()
}

func InitRedis() *redis.Client{
	if redisClient!= nil {
		return redisClient
	}
	redisAddr := beego.AppConfig.String("redis.addr")
	redisDb, _ := beego.AppConfig.Int("redis.db")
	redisClient = redis.NewClient(&redis.Options{
		Addr: redisAddr,
		DB:   redisDb,
	})
	_, err := redisClient.Ping().Result()
	if err!=nil {
		panic(err)
	}
	return redisClient
}

func SetString(key,value string)  {
	set := redisClient.Set(key, value, -1)
	if set.Err()!=nil{
		panic(set)
	}
}

func SetHashMap(key string,value map[string]interface{}) string {
	set := redisClient.HMSet(key, value)
	result, err := set.Result()
	if err!=nil{
		panic(err)
	}
	return result
}

func GetHashMap(key ,filed string) interface{} {
	get := redisClient.HMGet(key, filed)
	result, err := get.Result()
	if err!=nil{
		panic(err)
	}
	return result
}

func GetString(key string) string {
	get := redisClient.Get(key)
	if get.Err()!=nil{
		return "";
	}
	result, _ := get.Result()
	return result
}

func AddZSet(key, scoreKey string) {
	  val := redisClient.ZScore(key, scoreKey).Val()
	  val++
	  redisClient.ZAdd(key,redis.Z{Score: val,Member: scoreKey})
}

func GetScoreList(key string, start,end int64) [] string{
	getRange := redisClient.ZRange(key, start, end)
	if getRange.Err() != nil {
		panic(getRange.Err())
	}
	return getRange.Val()
}



// Subscribe 订阅消息
func Subscribe(channel string) *redis.Message {
	for  {
		subscribe := redisClient.Subscribe(channel)
		message, err := subscribe.ReceiveMessage()
		if err!=nil{
			panic(err)
		}
		ReciveMsg(message)
		subscribe.Close()
	}

}

// PublishMessage 发送消息
func PublishMessage(channel ,msg string) bool  {
	publish := redisClient.Publish(channel, msg)
	_, err := publish.Result()
	if err !=nil {
		return false
	}
	return true
}
